<?php

declare (strict_types=1);

namespace app\sys\controller;

use think\admin\Controller;
use think\admin\model\SysSms;
use think\admin\service\AlibabaSmsService;
use think\admin\service\TencentSmsService;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;

/**
 * 短信接口
 * Class Sms
 * @package app\system\controller
 */
class Sms extends Controller
{
    /**
     * 短信分页列表
     * @auth true
     * @return void
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function page()
    {
        $query = SysSms::mQuery();
        $query->where(['is_deleted' => 0]);

        // 数据列表搜索过滤
        $query->equal('status')->dateBetween('create_time');
        $query->like('phone');
        $query->dataScope('created_by');
        $lists = $query->order('id DESC')->page();
    }

    /**
     * 发送阿里云短信
     * @auth true
     * @return void
     */
    public function sendAliyun()
    {
        $data = $this->_vali([
            'phoneNumbers.require' => '接收手机号不能为空！',
            'templateCode.require' => '模板编码不能为空！',
            'templateParam.require' => '发送参数不能为空！',
            'signName.require' => '短信签名不能为空！',
        ]);
        $toSms = AlibabaSmsService::instance()->singleSendSms($data['phoneNumbers'], $data['templateCode'], $data['templateParam'], $data['signName']);
        if ($toSms) {
            $this->success('短信发送成功');
        } else {
            $this->error('短信发送失败');
        }
    }

    /**
     * 发送腾讯短信
     * @auth true
     * @return void
     */
    public function sendTencent()
    {
        $data = $this->_vali([
            'phoneNumbers.require' => '接收手机号不能为空！',
            'sdkAppId.require' => 'sdk appid不能为空',
            'templateCode.require' => '模板编码不能为空！',
            'templateParam.require' => '发送参数不能为空！',
            'signName.require' => '短信签名不能为空！',
        ]);
        $toSms = TencentSmsService::instance()->singleSendSms($data['phoneNumbers'], $data['sdkAppId'], $data['signName'], $data['templateCode'], $data['templateParam']);
        if ($toSms) {
            $this->success('短信发送完成，具体信息请看回执。');
        } else {
            $this->error('短信发送失败');
        }
    }

    /**
     * 获取短信详情
     * @auth true
     * @return void
     */
    public function detail()
    {
        $this->success('操作成功', SysSms::detail($this->request->param('id')));
    }

    /**
     * 移到回收站
     * @auth true
     * @return void
     */
    public function delete()
    {
        sysoplog('短信管理', '短信纪录删除成功');
        SysSms::mSave(['is_deleted' => 1]);
    }
}